package cn.com.yang.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.alibaba.fastjson.JSONObject;

/**
 * socket处理类
 * TODO
 * @author yangyijin
 * @since 2024年1月20日-下午4:57:06
 */
public class MyHandler implements Runnable {
	private Socket client;
	public MyHandler(Socket client) {
		this.client = client;
	}
	
	@Override
	public void run() {
		System.out.println("连接客户端："+client.getInetAddress().getHostAddress()+":port "+client.getPort());
		try(InputStream inputStream = client.getInputStream();
			OutputStream out = client.getOutputStream();){
			byte[] bytes = new byte[inputStream.available()];
            int result = inputStream.read(bytes);//
            if (result != -1) {
                System.out.println("字节输入流信息 ： 👇  👇  👇");
                System.out.println(new String(bytes));
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "you are right");
            String response = HTTPResponse.getResponseLine() + HTTPResponse.getResponseHeader() + "\n" + HTTPResponse.getResponseBody(jsonObject);
            out.write(response.getBytes());
            out.flush();
		}catch (Exception e) {
			System.out.println("异常：{}");
		}finally {
			if (client!=null) {
				try {
					client.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
